<?php
define('BASE_PATH', '../../');

function fail($errLog){
    output(
        [
            'code' => -1,
            'data' => $errLog
        ]
    );
}

function success($data){
    output(
        [
            'code' => 0,
            'data' => $data
        ]
    );
}

function output($data){
    header('Content-Type: application/json');
    if(is_array($data)){
        $data = json_encode($data);
    }
    echo $data;
    exit();
}

function display($tempPath, $data){
    header('Content-Type: text/html');
    extract($data);
    include $tempPath;
    exit();
}

function init(){
 
        $bodyRow = file_get_contents('php://input');
        $bodyArr = json_decode($bodyRow, true);
        
        if(isset($_GET['c']) && $_GET['c'] == 'schema'){
            $bodyArr = ['c'=>'apps', 'a'=>'get_app_schema', 'data'=>['app'=>$_GET['app'], 'page'=>$_GET['page']]];
        }
        
        if(isset($_GET['c']) && $_GET['c'] == 'preview'){
            $bodyArr = ['c'=>'apps', 'a'=>'preview_app_www', 'data'=>['app'=>$_GET['app'], 'page'=>$_GET['page'], 'version'=>$_GET['version']]];
        }
        
        if(empty($bodyArr) || !isset($bodyArr['c']) || !isset($bodyArr['a'])){
            fail('lose c or a!');
        }
        
        $controller = (string)$bodyArr['c'];
        $action = (string)$bodyArr['a'];
        $input = $bodyArr['data'];
        
        $controllerFilePath = BASE_PATH.'admin/apis/'.$controller.'.php';
        
        if(!file_exists($controllerFilePath)){
            fail('err c '. $controllerFilePath);
        }

        include_once($controllerFilePath);
        
        if(!function_exists($action)){
            fail('err a ' . $action);
        }
        
        $action($input);
}

init();